/*
 * @Description: 统一弹窗表单
 * @Author: Boide
 * @Date: 2021-09-09 15:47:47
 * @LastEditors: guiyi@hongyi.tech
 * @LastEditTime: 2021-09-16 13:08:44
 */
import http from '@/utils/request'
import { objToArray, objToArrayValue } from '@/utils/tools'
import Vue from 'vue'

let formRefs = ''
let unique = 1

const uniqueId = () => ++unique

/**
 * @description: 统一弹窗表单函数
 * @param {Promise} formRequestPromise Promise对象，返回表单的格式
 * @param {Object} formConf 弹窗配置参数
 * @return {*}
 */
export default function modalForm (formRequestPromise, formConf = {}) {
  const h = this.$createElement
  return new Promise((resolve, reject) => {
    formRequestPromise.then(async (data) => {
      let { data: { show } } = data
      const { page, url } = formConf
      if (['edit', 'detail'].includes(page)) {
        const res = await http.getHeader(`/api${url}`, {}, { getInfo: false, editFlag: page === 'edit' })
        data.formData = objToArrayValue(show, res.data, page === 'edit')
      } else if (page == 'custom') {
        // const res = await http.getHeader(url, {}, { getInfo: false, editFlag: page === 'edit' })
        data.formData = objToArray(show)
      } else {
        data.formData = objToArray(show)
      }
      data.formConf = { ...formConf }
      data = Vue.observable(data)
      this.$msgbox({
        title: data.formConf.showName,
        customClass: data.formConf.class || 'modal-form',
        message: h('div', { class: 'common-form-create', key: uniqueId() }, [
          h(page === 'detail' ? 'hy-form-detail' : 'hy-form', {
            props: {
              formData: data.formData,
              isModal: true
            },
            on: {
              mounted: ($f) => {
                formRefs = $f
              }
            }
          })
        ]),
        showCancelButton: true,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            // 获取表单dom,执行表单的validate事件验证表单表单字段填写是否正确
            formRefs.validate(valid => {
              instance.confirmButtonLoading = false
              if (!valid) return
              const fieldsArr = formRefs.fields
              const formData = {}
              fieldsArr.map(v => {
                formData[v.prop] = Array.isArray(v.fieldValue) ? v.fieldValue.join('@!#!@') : v.fieldValue
              })
              http.postJsonHeader('/api' + data.formConf.url, formData).then((res) => {
                done()
                this.$message.success(res.msg || '提交成功')
                resolve(res)
              }).catch(err => {
                this.$message.error(err.msg || '提交失败')
                reject(err)
              }).finally(() => {
                instance.confirmButtonLoading = false
              })
            })
          } else {
            instance.confirmButtonLoading = false
            done()
          }
        }
      })
    }).catch((e) => {
      this.$message.error(e.message)
    })
  })
}
